package com.ossfk.net.session;

import java.util.Date;
import java.util.Map;

import io.netty.channel.Channel;
import lombok.Data;

@Data
public class TcpSession {
	/** 会话唯一id */
	private String id;
	/** 远程连接地址 */
	private String remoteAddress;
	/** 远程手机号码 */
	private String phoneNum;
	/** 远程设备id */
	private String devid;
	/** 会话通道 */
	private Channel channel = null;	
	/** 会话消息流水号，按发送顺序从0 开始循环累加 */
	private volatile int currentFlowId = 0;
	// 上次的连接时间，该值改变的情况:
	// 1. terminal --> server 心跳包
	// 2. terminal --> server 数据包
	/** 创建时间 */
	private Date createTime=new Date();
	/** 上次的连接时间 */
	private long lastCommunicateTimeStamp = System.currentTimeMillis();
	/** 拓展属性 */
	private Map<String,Object> extandProperties;
	/** 会话是否已经死亡 */
	private boolean dead = false;
	
	public static String buildId(Channel channel) {
		if(channel==null)
			return "0";
		return channel.id().asLongText();
	}
	
	public static TcpSession buildSession(Channel channel) {
		return buildSession(channel, null);
	}

	public static TcpSession buildSession(Channel channel, String phone) {
		TcpSession session = new TcpSession();
		session.setChannel(channel);
		session.setId(buildId(channel));
		session.setLastCommunicateTimeStamp(System.currentTimeMillis());
		session.setRemoteAddress(channel.remoteAddress().toString());
		return session;
	}
	
	/**
	 * 
	 * @Description: 获取一个流水号后自动递增当前流水号
	 * @return
	 * @author Liujiefu
	 * @date 2020-03-16 16:45:13
	 */
	public synchronized int nextFlowId() {
		// 报文序号最大32位无符号整数
		if (currentFlowId >= Integer.MAX_VALUE)
			currentFlowId = 0;
		return currentFlowId++;
	}
}
